package cc.chinagps.gateway.client;


import cc.chinagps.gateway.client.protocol.Decoder;
import cc.chinagps.gateway.client.protocol.Msg;
import cc.chinagps.gateway.util.PropertiesUtil;

import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.net.JarURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class PackageScanner {
    Set<Class<?>> classes = new HashSet<>();
    Map<Byte, Decoder> msgDecoderMap = new HashMap<>();

    private PackageScanner() {
    }

    private static class SingletonHolder {
        private static final PackageScanner INSTANCE = new PackageScanner();
    }

    public static final PackageScanner getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public void init() throws Exception {
        scan(PropertiesUtil.getString("scan_package"));
        initMsgDecoderMap();
    }

    private void dealDirectory(String rootPackage, File curFile) {
        File[] fileList = curFile.listFiles();
        for (File file : fileList) {
            if (file.isDirectory()) {
                dealDirectory(rootPackage + "." + file.getName(), file);
            } else if (file.isFile()) {
                dealClassFile(rootPackage, file);
            }
        }
    }

    private void dealClassFile(String rootPackage, File file) {
        String fileName = file.getName();
        if (fileName.endsWith(".class")) {
            fileName = fileName.replace(".class", "");
            try {
                doAddClass(rootPackage + "." + fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void dealJarPackage(URL url) {
        try {
            JarURLConnection connection = (JarURLConnection) url.openConnection();
            JarFile jarFile = connection.getJarFile();
            Enumeration<JarEntry> jarEntries = jarFile.entries();
            while (jarEntries.hasMoreElements()) {
                JarEntry jar = jarEntries.nextElement();
                if (jar.isDirectory() || !jar.getName().endsWith(".class")) {
                    continue;
                }
                String jarName = jar.getName();
                jarName = jarName.replace(".class", "");
                jarName = jarName.replace("/", ".");
                try {
                    doAddClass(jarName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void scan(String packageName) throws Exception {
        String packageDirName = packageName.replace('.', '/');
        String rootPackage = packageName;
        try {
            Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
            while (dirs.hasMoreElements()) {
                URL url = dirs.nextElement();
                String protocol = url.getProtocol();
                if ("file".equals(protocol)) {
                    URI uri = url.toURI();
                    File root = new File(uri);
                    dealDirectory(rootPackage, root);
                } else if ("jar".equals(protocol)) {
                    dealJarPackage(url);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void doAddClass(final String classsName) throws Exception {
        ClassLoader classLoader = new ClassLoader() {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                return super.loadClass(name);
            }
        };
        classes.add(classLoader.loadClass(classsName));
    }

    public <A extends Annotation> Set<Class<?>> getAnnotationClasses(Class<A> annotationClass) throws Exception {
        Set<Class<?>> classList = new HashSet<>();
        if (classes != null && classes.size() > 0) {
            for (Class<?> cls : classes) {
                if (cls.getAnnotation(annotationClass) != null) {
                    classList.add(cls);
                }
            }
        }
        return classList;
    }

    public void initMsgDecoderMap() throws Exception {
        Set<Class<?>> msgClasses = getAnnotationClasses(Msg.class);
        for (Class<?> cls : msgClasses) {
            Msg annotation = cls.getAnnotation(Msg.class);
            msgDecoderMap.put(annotation.msgId(), (Decoder) cls.newInstance());
        }
    }

    public Decoder getMsgDecoder(byte msgId) {
        return msgDecoderMap.get(msgId);
    }
}
